import { addAccount, batchAddAccount, getOperList, getRoleList } from '@/services/permissions/api';
import { OptType } from '@/utils/constants';
import { isNull, showMsg } from '@/utils/utils';
import { ModalForm, ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Card, Col, FormInstance, Row, Tabs } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import './style.less';

const OptForm: React.FC<any> = (props) => {
  const {
    handleModalVisible,
    handleAdd,
    superAdmin,
    optType = OptType.ADD,
    record = {},
    deptList = []
  } = props;
  const formRef = useRef<FormInstance>();
  const formRef1 = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [isSuper, setIsSuper] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [choiceDept, setChoiceDept] = useState('');
  const { initialState } = useModel('@@initialState');
  // const myStaff = isNull(initialState?.currentUser?.super_oper_entity) ? initialState?.currentUser : initialState?.currentUser?.super_oper_entity;
  const myStaff = initialState?.currentUser || {};
  // 角色列表
  const [roleList, setRoleList] = useState<{ label: string; value: string; }[]>([]);

  const [loading, setLoading] = useState(false);
  // 院内和非院内
  const [tabKey, setTabKey] = useState<string>('t1');

  const columns: ProColumns<PERMISSIONSAPI.AccountListItem>[] = [
    {
      title: '科室',
      dataIndex: 'hostial_dept_code',
      hideInTable: true,
      valueType: 'select',
      order: 3,
      fieldProps: {
        options: deptList.map(item => {
          return {
            label: `${item.dept_code}-${item.dept_name}`,
            value: item.dept_code,
            data: item,
          }
        }),
        showSearch: true,
        filterOption: true,
        placeholder: '请输入或选择'
      },
    },
    {
      title: '员工姓名',
      dataIndex: 'staff_name',
      order: 1,
    },
    {
      title: '员工工号',
      dataIndex: 'staff_code',
      order: 2,

    },
    {
      title: '工作类别',
      dataIndex: 'work_class_name',
      hideInSearch: true,
    },
    {
      title: '工作类别',
      dataIndex: 'work_class_code',
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        '1': '行政',
        '10': '临时工',
        '11': '系统管理员',
        '12': '病案人员',
        '13': '全文检索人员',
        '2': '后勤',
        '20': '财务',
        '21': '门诊收款员',
        '22': '住院收款员',
        '30': '医疗',
        '40': '护理',
        '50': '药剂',
        '60': '医技',
        '61': '特约',
        '62': '图书管理',
        '63': '物资管理',
        '64': '分诊',
        '65': '司机',
        '70': '医护',
        '8': '待定',
        '9': '工人',
      }
    }
  ];

  useEffect(() => {
    // 为了处理单选按钮样式问题
    setTimeout(() => {
      formRef.current?.resetFields();
      setTimeout(() => {
        if (myStaff.identity_type !== 'A') {
          setChoiceDept(myStaff.dept_code);
          fetchRole(myStaff.dept_code);
          formRef.current?.setFieldsValue({ dept_code: { label: myStaff.dept_name, value: myStaff.dept_code } });
        }
      }, 100);
    }, 500);
  }, []);

  const fetchRole = (dept_code) => {
    getRoleList({ current: 1, pageSize: 99999, dept_code }).then((res: PERMISSIONSAPI.RoleList) => {
      const data = res?.record_list?.map((item) => {
        return {
          label: item.role_name as string,
          value: item.role_id as string,
          dept_code: item.dept_code as string
        }
      });
      setRoleList(data || []);
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    })
  };

  const onFinish = async (values: any) => {
    if (tabKey === 't1') {
      // 添加院内账号
      addAccount1(values);
    } else if (tabKey === 't2') {
      // 添加非院内账号
      addAccount2(values);
    }
  };

  /**
   * 添加非院内账号
   * @param values
   */
  const addAccount2 = async (values: any) => {
    try {
      setLoading(true);
      await addAccount({
        ...values, dept_level: '1',
        dept_code: values.dept_code.value,
        dept_name: values.dept_code.label || values.dept_code.data.dept_name
      } as any);
      showMsg('已保存', 'success');
      formRef.current?.resetFields();
      if (myStaff.identity_type !== 'A') {
        formRef.current?.setFieldsValue({ dept_code: { label: myStaff.dept_name, value: myStaff.dept_code } });
      }
      handleModalVisible(false);
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 添加院内账号
   * @param values
   */
  const addAccount1 = async (values: any) => {
    console.log('values', values, selectedRows)
    const params = {
      ...values,
      oper_list: selectedRows.map(item => { return { oper_name: item.staff_name, staff_code: item.staff_code } }),
      dept_code: values.dept_code.value,
      dept_name: values.dept_code.label || values.dept_code.data.dept_name,
    }
    console.log('params', params);
    setLoading(true);
    await batchAddAccount(params).then(res => {
      showMsg('已保存', 'success');
      formRef.current?.resetFields();
      formRef1.current?.submit();
      actionRef.current?.clearSelected?.();
      if (myStaff.identity_type !== 'A') {
        setChoiceDept(myStaff.dept_code);
        formRef.current?.setFieldsValue({ dept_code: { label: myStaff.dept_name, value: myStaff.dept_code } });
      } else {
        setRoleList([]);
      }
      setSelectedRows([]);
      handleModalVisible(true);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    }).finally(() => {
      setLoading(false);
    })
  };

  const deptSelect = (
    <Row>
      <Col span={24}>
        <ProFormSelect
          rules={[{ required: true }]}
          label="分配至业务科室"
          placeholder="请选择"
          width="md"
          name="dept_code"
          labelCol={{ flex: '0 0 110px' }}
          wrapperCol={{ flex: '0 0 calc(42% - 50px)' }}
          options={deptList.map(item => {
            return {
              label: `${item.dept_code}-${item.dept_name}`,
              value: item.dept_code,
              data: item,
            }
          })}
          fieldProps={{
            labelInValue: true,
            onSelect: (v) => {
              formRef.current?.setFieldsValue({ role_id: null })
              setChoiceDept(v.value);
              fetchRole(v.value)
            },
            onClear: () => {
              formRef.current?.setFieldsValue({ role_id: null, dept_code: [] });
              setChoiceDept('');
            },
            showSearch: true,
            filterOption: true,
            placeholder: '请输入或选择',
            disabled: myStaff.identity_type !== 'A',
          }}
        />
      </Col>
    </Row>
  );

  return <ModalForm
    formRef={formRef}
    title={false}
    width="70%"
    visible
    className="account-modal-edit"
    layout="horizontal"
    modalProps={{ maskClosable: false, bodyStyle: { paddingTop: 0 } }}
    onVisibleChange={handleModalVisible}
    onFinish={onFinish}
    submitter={{
      render: (props, doms) => {
        return [
          <Button key="cancel" onClick={() => {
            handleModalVisible(false);
          }}>取消</Button>,
          <Button loading={loading} key="save" type="primary" onClick={() => { props.form?.submit(); }}>保存</Button>
        ]
      }
    }}
  >
    <Tabs destroyInactiveTabPane={true} onChange={setTabKey} activeKey={tabKey}>
      <Tabs.TabPane tab='编辑院内账户' key='t1'>
        <Card title="1.账号信息" bordered={false} headStyle={{ padding: '0 6px' }} bodyStyle={{ padding: '12px 6px' }}>
          {deptSelect}
          <ProTable<PERMISSIONSAPI.AccountListItem, COMMON.PageParams & PERMISSIONSAPI.AccountListItem>
            actionRef={actionRef}
            formRef={formRef1}
            bordered
            rowKey="staff_code"
            cardProps={{ bodyStyle: { padding: 0 } }}
            search={{
              span: 4,
              collapsed: false,
              labelWidth: 'auto',
              className: 'insiders-table-search',
              optionRender: () => ([
                <Button type='primary' disabled={isNull(choiceDept)} onClick={() => formRef1.current?.submit()}>查询</Button>
              ])
            }}
            request={async (params) => {
              try {
                console.log('params', params)
                const data: PERMISSIONSAPI.AccountList = await getOperList({ ...params, dept_code: '' });
                return {
                  data: data.record_list,
                  success: true,
                  total: data.sum_record_num
                };
              } catch (error) {
                showMsg(error?.data?.errmsg);
                return {
                  data: [],
                  success: true,
                  total: 0
                };
              }
            }}
            columns={columns}
            options={false}
            pagination={false}
            scroll={{ y: window.innerHeight - 530 < 136 ? 136 : 320 }}
            manualRequest
            rowSelection={{
              columnWidth: 30,
              onChange: (sel, row) => {
                console.log('row', row)
                setSelectedRows(row);
                if (row.length > 1) {
                  formRef.current?.setFieldsValue({ identity_type: 'P' });
                }
              },
            }}
          />
        </Card>
      </Tabs.TabPane>
      <Tabs.TabPane tab='编辑非院内账户' key='t2'>
        <Card title="1.账号信息" bordered={false} headStyle={{ padding: '0 6px' }} bodyStyle={{ padding: '12px 6px' }}>
          {deptSelect}
          <Row gutter={12}>
            <Col span={8}>
              <ProFormText label="员工姓名" name="oper_name" labelCol={{ flex: '0 0 110px' }} required rules={[{ required: true }]} />
            </Col>
            <Col span={7}>
              <ProFormText label="登录手机号" name="mobile" labelCol={{ flex: '0 0 80px' }} required rules={[{ required: true }]} />
            </Col>
            <Col span={8}>
              <ProFormText.Password
                label="登录密码" name="login_pwd"
                fieldProps={{ visibilityToggle: true }}
                labelCol={{ flex: '0 0 80px' }}
                required={true} rules={[{ required: true }]}
              />
            </Col>
          </Row>
        </Card>
      </Tabs.TabPane>
    </Tabs>
    <Card title="2.角色信息" bordered={false} headStyle={{ padding: '0 6px' }} bodyStyle={{ padding: '12px 6px' }}>
      <ProFormSelect
        rules={[{ required: true }]}
        label="角色分配"
        placeholder="请选择"
        width="md"
        name="role_id"
        initialValue={record.role_id}
        options={roleList}
        labelCol={{ flex: '0 0 110px' }}
        wrapperCol={{ flex: '0 0 calc(42% - 50px)' }}
      />
      {
        tabKey === 't1' &&
        <ProFormRadio.Group
          rules={[{ required: true }]}
          label="是否为管理员"
          name="identity_type"
          labelCol={{ flex: '0 0 110px' }}
          initialValue={record.identity_type || 'P'}
          fieldProps={{
            onChange: (e: any) => {
              setIsSuper(e.target.value);
            }
          }}
          disabled={selectedRows.length > 1}
          options={[
            {
              label: '是',
              value: 'S'
            },
            {
              label: '否 （管理员账号会启用角色管理和账号管理功能，每科室限1名管理员）',
              value: 'P'
            }
          ]}
        />
      }
      <ProFormRadio.Group
        rules={[{ required: true, message: '请选择账号状态' }]}
        label="账号状态"
        name="status"
        labelCol={{ flex: '0 0 110px' }}
        initialValue={record.status || 'N'}
        options={[
          {
            label: '启用',
            value: 'N'
          },
          {
            label: '停用',
            value: 'S'
          }
        ]}
      />
    </Card>
  </ModalForm >
}
export default OptForm;
